package com.flashcash.solu.common.network;

import com.flashcash.solu.bean.ResponseErrorBody;
import com.google.gson.Gson;
import com.x.leo.apphelper.log.XLog;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * Created by XLEO on 2018/2/24.
 */

public abstract class HttpErrorHandledSubScriber<T> extends Subscriber<T> {
    @Override
    public void onError(Throwable e) {
        if (e instanceof HttpException) {
            try {
                Gson gson = new Gson();
                HttpException httpException = (HttpException) e;
                String errorBody = httpException.response().errorBody().string();
                ResponseErrorBody responseErrorBody = gson.fromJson(errorBody, ResponseErrorBody.class);
                onFinalError(new InterceptorException(responseErrorBody.getMessage()));
            } catch (Exception e1) {
                XLog.INSTANCE.i("handle http error Exception:" + e1.getMessage(), 10);
                onFinalError(e);
            }
        } else {
            onFinalError(e);
        }
    }

    @Override
    public void onCompleted() {
    }

    public abstract void onFinalError(Throwable e);
}
